package org.springsource.controllers;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.twitter.api.CursoredList;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.TwitterProfile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/twitter")
public class TwitterController {
	private static final Logger logger = LoggerFactory.getLogger(TwitterController.class);
	@Autowired
	private Twitter twitter;
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/friends", method = RequestMethod.GET)
	public String home(Principal currentUser, Model model) {
		logger.info("Welcome home! the client locale is ");
		CursoredList<TwitterProfile> profiles = twitter.friendOperations().getFriends();
		model.addAttribute("account", profiles);
		List<Tweet> tweets = twitter.timelineOperations().getHomeTimeline();
		for(Tweet tweet : tweets){
			logger.info("source:"+tweet.getSource());
			logger.info("text:"+tweet.getText());
			logger.info("size:"+tweet.getText().length());
			/*String[] arr = tweet.getText().split(" ");
			for(String s : arr){
				String extractedUrl = StringUtilityDashes.extractUrls(s);
				if(extractedUrl != ""){
					tweet.setText(tweet.getText().replace(s, "<a href=\'"+extractedUrl+"\'>"+extractedUrl+"</a>"));
				}
			}*/
		}
		model.addAttribute("tweets",tweets);
		return "twitter.friends";
	}
	
	@RequestMapping(value="/friendsJson", method = RequestMethod.GET)
	public @ResponseBody List<String> getFriends(){
		List<String> friendNames = new ArrayList<String>();
		for(TwitterProfile profile : twitter.friendOperations().getFriends()){
			friendNames.add(profile.getName());
		}
		return friendNames;
	}
	
	@RequestMapping(value = "/{userId}/tweets", method = RequestMethod.GET)
	public @ResponseBody
	List<Tweet> getTweetsByUserId(@PathVariable String userId) {
		return StringUtils.isNumeric(userId) ? twitter.timelineOperations()
				.getUserTimeline(Long.valueOf(userId)) : twitter
				.timelineOperations().getUserTimeline(userId);
	}
	
	
}

